<template>
  <div class="problemList">
    <div class="p-header">
      <div class="p-h-title"><i class="iconfont icon-timu-04"></i>题目列表</div>
    </div>
    <div class="p-search">
      <n-input class="p-s-input" placeholder="搜索题目" round size="small" v-model:value="searchVal">
        <template #suffix>
          <i class="iconfont icon-sousuo" @click="updateSearchParams"></i>
        </template>
      </n-input>
      <n-select class="p-s-select" size="small" v-model:value="problemParams.auth" :options="authOptions"></n-select>
      <n-button v-if="$store.oj.premission.includes('manage:prb:add')" class="p-s-btn" size="small" round type="success"
        @click="hanlderToCreate"><i class="iconfont icon-tianjia"></i>创建</n-button>
      <n-button v-if="$store.oj.premission.includes('manage:prb:add')" class="p-s-btn" size="small" round type="info"
        @click="showUploadFile"><i class="iconfont icon-shangchuan"></i>导入题目</n-button>
      <n-button v-if="$store.oj.premission.includes('manage:prb:add')" class="p-s-btn" color="#8a2be2" size="small"
        round @click="expireQuestion"><i class="iconfont icon-xiazai1"></i>导出题目</n-button>
      <div class="expire-type">
        导出类型:
        <n-select class="p-s-select" size="small" v-model:value="expireType" :options="expireOptions"></n-select>
      </div>
    </div>
    <div class="p-table">
      <el-table class="table problemTable" :data="problemList.records" size="small" stripe row-key="id"
        @selection-change="handleSelectionChange" @select="handleSelect" ref="problemTable">
        <el-table-column type="selection" width="55" reserve-selection />
        <el-table-column type="index" label="序号" width="100%" align="center" :index="indexMethod" />
        <el-table-column prop="id" label="ID" align="center"></el-table-column>
        <el-table-column prop="problemId" label="展示ID" align="center"></el-table-column>
        <el-table-column prop="title" label="标题" align="center"></el-table-column>
        <el-table-column prop="author" label="作者" align="center"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" align="center"></el-table-column>
        <el-table-column prop="auth" label="权限" align="center">
          <template #default="scoped">
            <n-select class="p-t-select" size="small" v-model:value="scoped.row.auth" :options="authOptions2"
              @update:value="updateProblemAuth(scoped.row)"></n-select>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="120">
          <template #default="scoped">
            <div class="p-t-comparation">
              <n-button class="nbtn" v-if="$store.oj.premission.includes('manage:prb:update')" size="tiny" type="info"
                @click="hanlderToEdit(scoped.row.id)"><i class="iconfont icon-bianji"></i></n-button>
              <n-button class="nbtn" size="tiny" type="success" @click="handlerToProblemList(scoped.row.id)"><i
                  class="iconfont icon-chakan1"></i></n-button>
              <n-popconfirm positive-text="确认" negative-text="取消" @positive-click="deleteProblem(scoped.row.id)"
                v-if="$store.oj.premission.includes('manage:prb:del')">
                <template #trigger>
                  <n-tooltip trigger="hover">
                    <template #trigger>
                      <n-button class="nbtn" size="tiny" type="error"><i class="iconfont icon-shanchu"></i></n-button>
                    </template>
                    删除
                  </n-tooltip>
                </template>
                确认删除题目？
              </n-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="p-footer">
      <el-pagination class="pagination" :page-sizes="[20, 50, 100]" background small layout="prev, pager, next,sizes"
        :total="Number(problemList.total)" v-model:current-page="problemParams.pageNum"
        v-model:page-size="problemParams.pageSize" />
    </div>
    <uploadQuestionDialog ref="uploadQuestion" @showTask="showTask"></uploadQuestionDialog>
    <showTaskDialog ref="showTask"></showTaskDialog>
  </div>
</template>

<script>
import {
  getProblemListAPI,
  updateProblemAuthAPI,
  deleteProblemAPI,
  expireProblemAPI
} from "@/api/adminAPI/adminAPI";
import { ElMessage } from "element-plus";
import uploadQuestionDialog from '@/components/adminComponents/uploadQuestionDialog/uploadQuestionDialog.vue'
import showTaskDialog from "@/components/adminComponents/showTaskDialog/showTaskDialog.vue";

export default {
  data() {
    return {
      problemList: {
        records: [],
        total: 20,
      },
      problemParams: {
        pageNum: 1,
        pageSize: 20,
        title: "",
        auth: "",
      },
      searchVal: "",
      authOptions: [
        {
          label: "全部题目",
          value: "",
        },
        {
          label: "公开题目",
          value: 1,
        },
        {
          label: "私有题目",
          value: 2,
        },
        {
          label: "比赛题目",
          value: 3,
        },
      ],
      authOptions2: [
        {
          label: "公开题目",
          value: 1,
        },
        {
          label: "私有题目",
          value: 2,
        },
        {
          label: "比赛题目",
          value: 3,
        },
      ],
      choiseQuestion: [],
      expireOptions: [
        {
          label: "JSON格式",
          value: 'JSON',
        },
        {
          label: "ZIP格式",
          value: 'ZIP',
        },
      ],
      expireType: 'JSON',
      debounceTime: null
    };
  },
  mounted() {
    this.getProblemList();
  },
  methods: {
    async getProblemList() {
      await getProblemListAPI(this.problemParams)
        .then((res) => {
          if (res.data.code === 200) {
            this.problemList = res.data.data;
          }
        })
        .catch((err) => {
          console.log("系统错误");
        });
    },
    updateSearchParams() {
      this.problemParams.title = this.searchVal;
    },
    hanlderToCreate() {
      this.$router.push({
        path: "/admin/problem/create",
      });
    },
    async updateProblemAuth(row) {
      const a = {
        pid: row.id,
        auth: row.auth,
      };
      await updateProblemAuthAPI(a)
        .then((res) => {
          if (res.data.code === 200) {
            this.getProblemList();
          }
        })
        .catch((err) => {
          console.log("系统错误");
        });
    },
    hanlderToEdit(id) {
      this.$router.push({
        path: `/admin/problem/list/${id}/edit`,
      });
    },
    handlerToProblemList(id) {
      this.$router.push({
        path: `/home/bank/${id}`,
      });
    },
    async deleteProblem(id) {
      await deleteProblemAPI([id])
        .then((res) => {
          if (res.data.code === 200) {
            ElMessage.success(res.data.msg);
            this.getProblemList();
          }
        })
        .catch((err) => {
          console.log("系统错误");
        });
    },
    indexMethod(index) {
      return (
        (this.problemParams.pageNum - 1) * this.problemParams.pageSize +
        index +
        1
      );
    },
    showUploadFile() {
      this.$refs.uploadQuestion.open()
    },
    // 处理选中变化
    handleSelectionChange(val) {
      this.choiseQuestion = val;
    },
    // 处理单个选中
    handleSelect(selection, row) {
      if (selection.includes(row)) {
        // 选中
        if (!this.choiseQuestion.some(item => item.id === row.id)) {
          this.choiseQuestion.push(row);
        }
      } else {
        // 取消选中
        this.choiseQuestion = this.choiseQuestion.filter(item => item.id !== row.id);
      }
    },
    // 切换分页时恢复选中状态
    onPageChange() {
      this.$nextTick(() => {
        this.choiseQuestion.forEach(row => {
          this.$refs.problemTable.toggleRowSelection(row, true);
        });
      });
    },
    expireQuestion() {
      if (this.debounceTime) {
        clearTimeout(this.debounceTime)
        this.debounceTime = null
      }
      this.debounceTime = setTimeout(() => {
        this.expireQuestionList()
      }, 400)
    },
    async expireQuestionList() {
      if (this.choiseQuestion.length == 0) {
        ElMessage.error("请选择需导出的题目")
        return
      }
      const ids = this.choiseQuestion.map(item => item.id)
      try {
        const response = await expireProblemAPI(ids, this.expireType)
        const { code, data, msg } = response.data
        if (code == 200) {
          this.$refs.problemTable.clearSelection()
          this.$refs.showTask.open([data])
        }
      } catch (err) {
        console.log(err)
      }
    },
    showTask(data = []) {
      if (!data.length) {
        return
      }
      this.$refs.showTask.open(data)
    }
  },
  watch: {
    problemParams: {
      deep: true,
      handler(newV) {
        this.getProblemList();
      },
    },
  },
  components: {
    uploadQuestionDialog,
    showTaskDialog
  }
};
</script>

<style lang="less" scoped>
.problemList {
  margin: auto;
  width: 96%;
  height: 92vh;
  padding: 10px;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 12px 12px 50px #d9d9d9, -12px -12px 50px #ffffff;
  display: flex;
  flex-direction: column;

  .p-header {
    display: flex;

    .p-h-title {
      height: 30px;
      line-height: 30px;
      font-size: 20px;
      font-weight: 600;
      color: #555;
      display: flex;
      text-align: center;

      .iconfont {
        margin: auto 0;
        font-weight: 700;
        font-size: 28px;
        height: 30px;
      }
    }
  }

  .p-search {
    display: flex;
    height: 30px;
    line-height: 30px;
    margin: 20px 0 0 0;
    padding-bottom: 10px;
    border-bottom: 2px solid @lineColor;

    .p-s-input {
      height: 30px;
      line-height: 30px;
      width: 20%;
    }

    .p-s-select {
      width: 13%;
      height: 30px;
      line-height: 30px;
      margin: auto 10px;
    }

    .p-s-btn {
      padding: 0px 20px;
      margin-left: 20px;
    }

    .expire-type {
      display: flex;
      align-items: center;
      text-wrap: nowrap;
      margin-left: 10px;

      .p-s-select {
        min-width: 110px;
      }
    }
  }

  .p-table {
    width: 100%;
    margin: 10px auto 0 auto;

    .table {
      height: 72vh;
    }

    .p-t-time {
      display: flex;
      flex-direction: column;

      .time {
        color: black;
      }
    }

    .p-t-comparation {
      display: flex;

      .nbtn {
        margin: auto 2px;
      }
    }
  }

  .p-footer {
    margin: auto auto 0 auto;
    display: flex;
    justify-content: center;
  }
}
</style>
